<?php
/**********************************************************************************
	
	List all purchases from the database
	
	Copyright (C) 2010 Benjamin Thomas
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 	Author: Benjamin Thomas
	Email: thomas.ben@gmail.com
	Created: 07.03.10
 
	Inputs: 
		graph_limit - Number of days to display on graph (default is 7)
		p - Page to display out of results
	Calls: None.
 
 **********************************************************************************
 */
require_once(dirname(__FILE__) . '/../../lib/PageLayout.php');
require_once(dirname(__FILE__) . '/../../lib/dateFunctions.php');
require_once(dirname(__FILE__) . '/../../lib/MarketDB.php');

$table_limit = 7000;
$graph_limit = 7;
$graph_limit_max = 30;
$graph_limit_accept = array(7, 14, 30);
$oneDay = 60*60*24;
if (array_key_exists('limit', $_GET)) {
	$graph_limit = intval($_GET['limit']);
	if ( in_array($graph_limit,$graph_limit_accept) == false ) {
		$graph_limit = 14;
	} elseif ($_GET['limit'] > $graph_limit_max) {
		$graph_limit = $graph_limit_max;
	} 
}
if (array_key_exists('id', $_GET)) {
	$id = intval($_GET['id']);
} else { 
	$id = false;
}


// Instance a new Database
$marketDB = new MarketDB();
$marketDB->loadItems();

if ($id) {	
	$auctions = $marketDB->getPurchases($graph_limit,$id);
	$summary = $marketDB->getPurchasesSummary($graph_limit,$id);
} else {
	$auctions = $marketDB->getPurchases($graph_limit);
	$summary = $marketDB->getPurchasesSummary($graph_limit);
}
for ($i = 0; $i < count($auctions); $i++) {
	$temp = array();
	if (!$id) {
		$item = $auctions[$i]['itemID'];
		if (!$icon = $marketDB->items[$item]['icon']) {
			$icon = "404.png";
		}

		$desc = '<img src="images/icons/'. $icon . '" style="height:20px; width: 20px; margin-right: 5px;" />';
		$desc .= '<a href="#" class="link" onClick="showPurchases(' . $graph_limit . ',' . $item . ')">' . $marketDB->getItemName($item) . '</a>';
		$temp[] = $desc;
	}
	$temp[] = date("n/j/y g:i a", $auctions[$i]['time']);
	$temp[] = date("l", $auctions[$i]['time']);
	$temp[] = utf8_encode($auctions[$i]['seller']);
	$temp[] = $auctions[$i]['stackCount'];
	$temp[] = getGold(floor($auctions[$i]['price'] / $auctions[$i]['stackCount']));
	$tableData[] = $temp;
	unset($temp);
}
$dailyFreq = createTimestampArray($graph_limit,0);
$dailyCounts = createTimestampArray($graph_limit,0);
foreach($summary as &$row) {
	$i = array_search(array(strtotime($row['day']) * 1000,0), $dailyCounts);
	$dailyCounts[$i][1] = $row['spent'] / 10000;
	$dailyFreq[$i][1] = $row['total'];
}
unset($summary);

$top = array();
if ($id) {
	if (!$icon = $marketDB->items[$id]['icon']) {
		$icon = "404.png";
	}
	echo '<img src="images/icons/'. $icon . '" style="height:20px; width: 20px; margin-right: 5px;" /> ' . $marketDB->items[$id]['name'] . "<br />";
	$top[] = "<a href='#' onClick='showPurchases($graph_limit)' class='small'><< Back to Purchases</a>";
	if ($graph_limit != 7) { $top[] =  "<a href='#' onClick='showPurchases(7,$id)' class='small'>Last 7 Days</a>"; }
	if ($graph_limit != 14) { $top[] = "<a href='#' onClick='showPurchases(14,$id)' class='small'>Last 14 Days</a>"; }
	if ($graph_limit != 30) { $top[] =  "<a href='#' onClick='showPurchases(30,$id)' class='small'>Last 30 Days</a>"; }
} else {		
	print "Purchase Data<BR>";
	if ($graph_limit != 7) { $top[] =  "<a href='#' onClick='showPurchases(7)' class='small'>Last 7 Days</a>"; }
	if ($graph_limit != 14) { $top[] = "<a href='#' onClick='showPurchases(14)' class='small'>Last 14 Days</a>"; }
	if ($graph_limit != 30) { $top[] =  "<a href='#' onClick='showPurchases(30)' class='small'>Last 30 Days</a>"; }
}
echo  implode(" | ", $top);
unset($top);
print "<hr />";
print "<div style='width: 900px; text-align: center;'></div>";
print '<div id="placeholder" class="graph" style="width:900px;height:300px; text-align:center">';
print "<img src='images/indicator.gif' style='margin-left: auto; margin-right: auto' alt='loading...' />";
print '<br />Your graph is loading.</div>' . "\n\n";

echo '<div>';
?>
<div id="pager" class="pager" style="text-align:right; magin-top: 10px; margin-bottom: -15px;"> 
	<form> 
		<img src="images/first.png" class="first"/> 
		<img src="images/prev.png" class="prev"/>
		<span style="color: black" class="pagedisplay"></span>
		<img src="images/next.png" class="next"/> 
		<img src="images/last.png" class="last"/> 
		<select class="pagesize"> 
			<option  value="10">10</option> 
			<option selected="selected"  value="20">20</option> 
			<option value="30">30</option> 
			<option  value="40">40</option> 
		</select> 
	</form> 
</div> 
<?php
echo '<table id="purchases" class="tablesorter">' . "\n";
echo '<thead>' . "\n";
echo '<tr>' . "\n";
//$headings = array("", "Item", "Time", "Day", "Agent", "Value", "Qty", "Rate");
if (!$id) { echo '<th>Item</th>'; }
echo '<th>Time</th><th>Day</th><th>Seller</th><th style="width: 40px;">Qty</th><th style="width: 100px;">Rate</th>' . "\n";
echo '</tr>' . "\n";
echo '</thead>' . "\n";
echo '<tbody>' . "\n";
if (!isset($tableData)) {
	echo '</tbody></table>';
	echo '<div style="width: 300px; text-align:center; margin-left: auto; margin-right: auto;">No results found</div>';
} else {
	foreach($tableData as &$row) {
		echo '<tr>';
		foreach($row as &$val) {
			if (!$val) { $val = "&nbsp;"; }
			echo '<td> ' . $val . ' </td>';
		}
		echo '</tr>' . "\n";
	}
	echo '</tbody>' . "\n";
	echo '</table>' . "\n";
}
echo '</div>';
?>

<script id="source" language="javascript" type="text/javascript">
$(function () {
	$('#placeholder').bind('click', function() { $(".legend").toggle(); });
	var rd = [];
	rd[0] = <?php echo json_encode($dailyFreq); ?>;
	rd[1] = <?php echo json_encode($dailyCounts); ?>;
	
   	for (var j = 0; j < rd.length; ++j)
		for (var i = 0; i < rd[j].length; ++i)
			rd[j][i][0] +=  <?php echo getOffset(); ?> * 1000;
			
    var options = {
        xaxis: { mode: "time", timeformat: "%m/%d",  },
		yaxes: [
			{ position: 'left' },
			{ position: 'right' },			
		],
		yaxis: { min: 0 },
		legend: { position: 'nw' },
		grid: { hoverable: true }
    };
	
	var d = [
		{ data: rd[0], type: 'int',	label: "Completed Auctions", color: "rgb(237,194,64)", yaxis: 2, bars: { show: true, align: 'center', barWidth: 60*60*24*1000 }, lines: { show: false } },
		{ data: rd[1], type: 'gold', label: "Gold Spent", color: "rgb(203,75,75)",lines: { show: true } }
	]
	
    var plot = $.plot($("#placeholder"), d, options);

    var previousPoint = null;
	var monthname=new Array("January","February","March","April","May","June","July","August","September","Octber","November","December");
    $("#placeholder").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));
 
		if (item) {
			if (previousPoint != item.datapoint) {
				previousPoint = item.datapoint;
				
				$("#tooltip").remove();
				var x = new Date(item.datapoint[0]);
				x = monthname[x.getMonth()] + " " + x.getDate();
				var y = item.datapoint[1];
				showToolTip(item, x, y);
			}
		}
		else {
			$("#tooltip").remove();
			previousPoint = null;            
		}
    });  
	$(".legendColorBox").die("click");
});
</script> 
<script>
	
$(document).ready(function() 
    {     
		$.tablesorter.addParser({ 
        id: 'item', 
        is: function(s) { 
            return false; 
        }, 
        format: function(s) {
			return s.match( /<a.*href=\"(.*?)\".*?\>(.*)\<\/a\>+/)[2];
        }, 
        type: 'text' 
		}); 
		$.tablesorter.addParser({ 
        id: 'gold', 
        is: function(s) { 
            return false; 
        }, 
        format: function(s) {
			var val = 0;
			var tmp = s.match( /(\d*)<img.*gold/ );	if (tmp) { val += (tmp[1] *  10000); }
			var tmp = s.match( /(\d*)<img.*silver/ );	if (tmp) { val += (tmp[1] *  100); }
			var tmp = s.match( /(\d*)<img.*copper/ );	if (tmp) { val += tmp[1]; }
			return val;
        }, 
        type: 'numeric' 
		});
		$.tablesorter.addParser({ 
		id: 'weekday', 
		is: function(s) { 
			return false; 
		}, 
		format: function(s) {
			var val = 0;
			
			switch (s) {
				case ' Sunday ': val =  1; break;
				case ' Monday ': val = 2; break;
				case ' Tuesday ': val = 3; break;
				case ' Wednesday ': val = 4; break;
				case ' Thursday ': val = 5; break;
				case ' Friday ': val = 6; break;
				case ' Saturday ': val = 7; break;
			}
			return val;
		}, 
		type: 'numeric' 
	}); 		
		$(function() { 
        $("#purchases").tablesorter({ 
			sortList: [[<?php if ($id) { echo 0; } else { echo 1; } ?>,1]],
            headers: { 
<?php
if ($id) {
	echo "1: { sorter:'weekday' },";
	echo "4: { sorter:'gold' },";
} else {
	echo "0: { sorter:'item' },";
	echo "2: { sorter:'weekday' },";
	echo "5: { sorter:'gold' }";
} 
?>
            },
			widthFixed: true,
			widgets: ['zebra']			
        }); 
		$("#purchases").tablesorterPager({container: $("#pager")});
    });      

    } 
); 
    
</script>